package com.niuxiaofa.newlaw.Fragment;

import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTDrawFeedAd;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.niuxiaofa.newlaw.Base.BaseFragment;
import com.niuxiaofa.newlaw.Base.RefreshInterface;
import com.niuxiaofa.newlaw.Bean.VideoListBean;
import com.niuxiaofa.newlaw.Network.PublicPresenter;
import com.niuxiaofa.newlaw.R;
import com.niuxiaofa.newlaw.Tools.GetLog;
import com.niuxiaofa.newlaw.Tools.OnViewPagerListener;
import com.niuxiaofa.newlaw.Tools.TTAdManagerHolder;
import com.niuxiaofa.newlaw.Tools.UIUtils;
import com.niuxiaofa.newlaw.Tools.ViewPagerLayoutManager;
import com.niuxiaofa.newlaw.View.CommonPopWindow;
import com.niuxiaofa.newlaw.adapter.SmaillAdapter;
import com.niuxiaofa.newlaw.video.JzvdStdTikTok;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.jzvd.Jzvd;

/**
 *
 * 视频
 */
public class EnergyFragment extends BaseFragment implements PublicPresenter.interface_getVideoList, RefreshInterface.Refresh, CommonPopWindow.ViewClickListener {

    int currentIndex = 1;
    private int mCurrentPosition = -1;
    SmaillAdapter smaillAdapter;

    private ViewPagerLayoutManager mViewPagerLayoutManager;

    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;

    List<VideoListBean.DataDTO.ListDTO> listDTOS = new ArrayList<>();
    TTAdNative mTTAdNative;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_videolist;
    }


    public void startplayvideo() {
        currentIndex = 1;
        PublicPresenter.getVideoList(currentIndex, this);

    }


    @Override
    public void initData() {

        mTTAdNative = TTAdManagerHolder.get().createAdNative(getActivity());
        refreshinterface = new RefreshInterface(this);

        smaillAdapter = new SmaillAdapter(listDTOS, new SmaillAdapter.Onclick() {
            @Override
            public void onclick(int c) {

                CommonPopWindow.newBuilder()
                        .setView(R.layout.pop_comment)
                        .setAnimationStyle(R.style.anim_menu_bottombar)
                        .setBackgroundDrawable(new BitmapDrawable())
                        .setSize(ViewGroup.LayoutParams.MATCH_PARENT, UIUtils.dp2px(getContext(), 400))
                        .setViewOnClickListener(EnergyFragment.this)
                        .setBackgroundDarkEnable(true)
                        .setBackgroundAlpha(0.7f)
                        .setBackgroundDrawable(new ColorDrawable(999999))
                        .build(getActivity())
                        .showAsBottom(recyclerview);

            }
        });

        mViewPagerLayoutManager = new ViewPagerLayoutManager(UIUtils.getContext(), OrientationHelper.VERTICAL);
        recyclerview.setLayoutManager(mViewPagerLayoutManager);
        recyclerview.setAdapter(smaillAdapter);


        mViewPagerLayoutManager.setOnViewPagerListener(new OnViewPagerListener() {
            @Override
            public void onInitComplete() {
                //自动播放第一条
                //   autoPlayVideo(0);
            }

            @Override
            public void onPageRelease(boolean isNext, int position) {
                if (mCurrentPosition == position) {
                    //   Jzvd.releaseAllVideos();
                }
            }

            @Override
            public void onPageSelected(int position, boolean isBottom) {
                if (mCurrentPosition == position) {
                    return;
                }

                GetLog.getLog(position + "");

                autoPlayVideo(position);

                mCurrentPosition = position;
            }
        });

        recyclerview.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
            @Override
            public void onChildViewAttachedToWindow(View view) {
                autoPlayVideo(0);
            }

            @Override
            public void onChildViewDetachedFromWindow(View view) {
                Jzvd jzvd = view.findViewById(R.id.videoplayer);
                if (Jzvd.CURRENT_JZVD.jzDataSource!=null){
                    if (jzvd != null && Jzvd.CURRENT_JZVD != null && jzvd.jzDataSource != null &&
                            jzvd.jzDataSource.containsTheUrl(Jzvd.CURRENT_JZVD.jzDataSource.getCurrentUrl())) {
                        if (Jzvd.CURRENT_JZVD != null && Jzvd.CURRENT_JZVD.screen != Jzvd.SCREEN_FULLSCREEN) {
                            Jzvd.releaseAllVideos();
                        }
                    }
                }
            }
        });


    }

    private void initAD() {
        //创建TTAdNative对象，createAdNative(Context context) context需要传入Activity对象

        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId("901121709")
                .setImageAcceptedSize(1080, 1920)
                .setAdCount(1) //请求广告数量为1到3条
                .build();


        mTTAdNative.loadDrawFeedAd(adSlot, new TTAdNative.DrawFeedAdListener() {
            @Override
            public void onError(int code, String message) {
                GetLog.getLog(message);

            }

            @Override
            public void onDrawFeedAdLoad(List<TTDrawFeedAd> ads) {


                VideoListBean.DataDTO.ListDTO listDTO = new VideoListBean.DataDTO.ListDTO();

                listDTO.setTtDrawFeedAd(ads.get(0));

                listDTOS.add(listDTO);

                smaillAdapter.notifyDataSetChanged();
//                if (ads == null || ads.isEmpty()) {
//                    TToast.show(DrawNativeVideoActivity.this, " ad is null!");
//                    return;
//                }
//                for (int i = 0; i < 5; i++) {
//                    int random = (int) (Math.random() * 100);
//                    int index = random % videos.length;
//                    datas.add(new Item(TYPE_COMMON_ITEM, null, videos[index], imgs[index]));
//                }
//
//                for (TTDrawFeedAd ad : ads) {
//                    ad.setActivityForDownloadApp(DrawNativeVideoActivity.this);
//                    //点击监听器必须在getAdView之前调
//                    ad.setDrawVideoListener(new TTDrawFeedAd.DrawVideoListener() {
//                        @Override
//                        public void onClickRetry() {
//                            TToast.show(DrawNativeVideoActivity.this, " onClickRetry !");
//                            Log.d("drawss", "onClickRetry!");
//                        }
//
//                        @Override
//                        public void onClick() {
//                            Log.d("drawss", "onClick download or view detail page ! !");
//                            TToast.show(DrawNativeVideoActivity.this, " setDrawVideoListener click download or view detail page !");
//                        }
//                    });
//                    ad.setCanInterruptVideoPlay(true);
////                    ad.setPauseIcon(BitmapFactory.decodeResource(mContext.getResources(), R.drawable.dislike_icon), 60);
//                    int random = (int) (Math.random() * 100);
//                    int index = random % videos.length;
//                    datas.add(index, new Item(TYPE_AD_ITEM, ad, -1, -1));
//                }
//                mAdapter.notifyDataSetChanged();
            }
        });
    }
    //请求广告
//        mTTAdNative.loadNativeExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
//
//            //广告请求失败
//            @Override
//            public void onError(int code, String message) {
//                GetLog.getLog("视频广告" + code + message);
//            }
//
//            //广告请求成功
//            @Override
//            public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
//                VideoListBean.DataDTO.ListDTO newlistDTO = new VideoListBean.DataDTO.ListDTO();
//                TTNativeExpressAd mTTAd = ads.get(0);
//                newlistDTO.setTtNativeExpressAd(mTTAd);
//                bindAdListener(mTTAd);
//                mTTAd.render();
//                listDTOS.add(newlistDTO);
//                smaillAdapter.notifyDataSetChanged();
//            }
    //        });
    // }

    private void bindAdListener(TTNativeExpressAd ad) {
        ad.setExpressInteractionListener(new TTNativeExpressAd.ExpressAdInteractionListener() {
            @Override
            public void onAdClicked(View view, int type) {
                Toast("广告被点击");
            }

            @Override
            public void onAdShow(View view, int type) {
                Toast("广告展示");
            }

            @Override
            public void onRenderFail(View view, String msg, int code) {
                Log.e("ExpressView", "render fail:" + (System.currentTimeMillis()));
                Toast(msg + " code:" + code);
            }

            @Override
            public void onRenderSuccess(View view, float width, float height) {
                Log.e("ExpressView", "render suc:" + (System.currentTimeMillis()));
                //返回view的宽高 单位 dp
                Toast("渲染成功");
                GetLog.getLog("渲染成功 " + width + " " + height);
//                mExpressContainer.removeAllViews();
//                mExpressContainer.addView(view);
            }
        });
        //dislike设置
//        bindDislike(ad, false);
        if (ad.getInteractionType() != TTAdConstant.INTERACTION_TYPE_DOWNLOAD) {
            return;
        }
        ad.setDownloadListener(new TTAppDownloadListener() {
            @Override
            public void onIdle() {
                Toast("点击开始下载");
            }

            @Override
            public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
//                if (!mHasShowDownloadActive) {
//                    mHasShowDownloadActive = true;
//                    TToast.show(NativeExpressActivity.this, "下载中，点击暂停", Toast.LENGTH_LONG);
//                }
            }

            @Override
            public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
                //  TToast.show(NativeExpressActivity.this, "下载暂停，点击继续", Toast.LENGTH_LONG);
            }

            @Override
            public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
                // TToast.show(NativeExpressActivity.this, "下载失败，点击重新下载", Toast.LENGTH_LONG);
            }

            @Override
            public void onInstalled(String fileName, String appName) {
                // TToast.show(NativeExpressActivity.this, "安装完成，点击图片打开", Toast.LENGTH_LONG);
            }

            @Override
            public void onDownloadFinished(long totalBytes, String fileName, String appName) {
                //  TToast.show(NativeExpressActivity.this, "点击安装", Toast.LENGTH_LONG);
            }
        });
    }


    /**
     * 自动播放
     */
    private void autoPlayVideo(int postion) {
        try {


            if (recyclerview == null || recyclerview.getChildAt(0) == null) {
                return;
            }

            JzvdStdTikTok player = recyclerview.getChildAt(0).findViewById(R.id.videoplayer);
            if (player != null) {
                player.startVideo();
            }
        } catch (Exception e) {

        }
    }


    @Override
    public void getResponse(VideoListBean u) {
        if (u.getCode() == 1) {

            if (currentIndex == 1) {
                listDTOS.clear();
            }
            if (refreshLayout != null) {
                refreshLayout.finishLoadMore();
                refreshLayout.finishRefresh();
            }
            if (u.getData().getList().size() == 0) {
                Toast("没有数据了");

            }
            listDTOS.addAll(u.getData().getList());
            initAD();
//            smaillAdapter.notifyDataSetChanged();
        }
    }


    @Override
    public void onStop() {
        super.onStop();
        Jzvd.releaseAllVideos();
    }

    @Override
    public void onPause() {
        super.onPause();
        Jzvd.releaseAllVideos();
    }

    int count = 1;

    @Override
    public void refresh() {
        currentIndex = 1;
        PublicPresenter.getVideoList(currentIndex, this);
    }

    @Override
    public void loadmore() {
        currentIndex++;

        PublicPresenter.getVideoList(currentIndex, this);

    }

    @Override
    public void getChildView(PopupWindow mPopupWindow, View view, int mLayoutResId) {

    }
}